package project.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * エラー時フィルタ
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class ErrorDispatchFilter implements Filter {

	/**
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(final FilterConfig filterConfig) throws ServletException {
		return;
	}

	/**
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		return;
	}

	/**
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(final ServletRequest svRequest, final ServletResponse svResponse,
			final FilterChain chain) throws IOException, ServletException {

		if (HttpServletRequest.class.isInstance(svRequest)) {
			HttpServletRequest request = HttpServletRequest.class.cast(svRequest);
			request.setAttribute(ErrorDispatchFilter.class.getName(), "ERROR");
		}

		chain.doFilter(svRequest, svResponse);
	}

	/**
	 * エラーディスパッチ確認
	 * @param request リクエスト
	 * @return エラー時 true を返す。
	 */
	public static boolean isErrorDispatch(final HttpServletRequest request) {
		return "ERROR".equals(request.getAttribute(ErrorDispatchFilter.class.getName()));
	}
}
